//
//  HJPageControl.m
//  TJPageControllTest
//
//  Created by lx on 2023/11/16.
//

#import "HJPageControl.h"


@interface HJPageControl ()

@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, assign) CGSize indicatorSize;

@end


@implementation HJPageControl


- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _indicatorSize = CGSizeMake(6, 3);
        
        UIView *contentView = [[UIView alloc] init];
        [self addSubview:contentView];
        _contentView = contentView;
    }
    return self;
}


- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat totalW = 0;
    CGFloat contentH = self.frame.size.height;
    [self.contentView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.frame = CGRectMake(idx * (self.indicatorSize.width + 3), (contentH - self.indicatorSize.height) * 0.5, self.indicatorSize.width, self.indicatorSize.height);
    }];
    totalW = CGRectGetMaxX(self.contentView.subviews.lastObject.frame);
    self.contentView.frame = CGRectMake((self.frame.size.width - totalW) * 0.5, (self.frame.size.height - contentH) * 0.5, totalW, contentH);
    
}

- (void)setCurrentPage:(NSInteger)currentPage {
    _currentPage = currentPage;
    
    [self.contentView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == currentPage) {
            obj.backgroundColor = self.currentPageIndicatorTintColor;
        } else {
            obj.backgroundColor = self.pageIndicatorTintColor;
        }
    }];
}

- (void)setCurrentPageIndicatorTintColor:(UIColor *)currentPageIndicatorTintColor {
    _currentPageIndicatorTintColor = currentPageIndicatorTintColor;
    
    self.currentPage = self.currentPage;
}

- (void)setPageIndicatorTintColor:(UIColor *)pageIndicatorTintColor {
    _pageIndicatorTintColor = pageIndicatorTintColor;
    self.currentPage = self.currentPage;
}

- (void)setNumberOfPages:(NSInteger)numberOfPages {
    _numberOfPages = numberOfPages;
    
    //创建子控件
    for (UIView * _Nonnull obj in self.contentView.subviews) {
        [obj removeFromSuperview];
    }
    
    for (int i = 0; i < numberOfPages; i++) {
        UIView *indicatorView = [[UIView alloc] init];
        indicatorView.layer.cornerRadius = self.indicatorSize.height * 0.5;
        indicatorView.layer.masksToBounds = YES;
        [self.contentView addSubview:indicatorView];
        
        if (i == self.currentPage) {
            indicatorView.backgroundColor = self.currentPageIndicatorTintColor;
        } else {
            indicatorView.backgroundColor = self.pageIndicatorTintColor;
        }
    }
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
}

@end
